<template>
  <el-container>
    <el-aside class="w-[200px] h-[100vh] bg-[#f0f0f0] overflow-auto">
      <fieldView />
    </el-aside>
    <el-main class="h-[100vh] overflow-auto">
      <el-drawer v-model="fieldStore.drawer" title="属性设置" direction="rtl">
        <settingsView @sort="onSort" @config="onConfig" />
      </el-drawer>

      <div class="common-layout">
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="list" name="list">
            <div class="p-4">
              <el-input type="textarea" :rows="10" placeholder="请输入JSON内容" v-model="jsonInput" class="mb-4" />
              <el-button type="primary" @click="onInit" class="w-full mb-4">
                确定
              </el-button>

              <h4>{{ dsName }}</h4>

              <div class="mt-8 p-4 shadow-lg" @click="fieldStore.setCurColumn(filterList)"
                :class="{ cos: fieldStore.curColumn == filterList }">

                <div class="flex gap-4 items-center p-4 bg-[#f0f0f0]">
                  <div class="text-lg text-nowrap">搜索</div>
                  <div class="text-nowrap">筛选：</div><el-input v-model="keyword"></el-input>
                </div>

                <div class="flex gap-4 items-center mt-4">
                  <!-- <el-button type="danger" @click="">清空</el-button> -->
                </div>

                <div class="flex gap-4 items-center mt-4 flex-wrap">
                  <el-tag v-for="tag in filterList" :type="tag == fieldStore.curField ? 'warning' : 'info'"
                    @click="fieldStore.setCurField(tag)" class="cursor-pointer" :key="tag.prop" closable
                    :disable-transitions="false" @close="tag.search = false">
                    {{ tag.label }}
                  </el-tag>
                </div>

                <div class="my-3 h-1 bg-[#999]"></div>

                <div class="flex gap-4 items-center mt-4 flex-wrap">
                  <el-tag v-for="tag in filterTags" type="success" class="cursor-pointer" @click="onAddSearch(tag)"
                    :key="tag.prop" :disable-transitions="false">
                    {{ tag.label }}
                  </el-tag>
                </div>
              </div>

              <div class="mt-8 p-4 shadow-lg" @click="fieldStore.setCurColumn(trList)"
                :class="{ cos: fieldStore.curColumn == trList }">
                <div class="flex gap-4 items-center p-4 bg-[#f0f0f0]">
                  <div class="text-lg text-nowrap">表格</div>
                  <div class="text-nowrap">筛选：</div><el-input v-model="keyword"></el-input>
                </div>

                <div class="flex gap-4 items-center mt-4">
                  <el-button type="danger" @click="trList = []">清空</el-button>
                </div>

                <div class="flex gap-4 items-center mt-4 flex-wrap">
                  <el-tag v-for="tag in trList" :type="tag == fieldStore.curField ? 'warning' : 'info'"
                    @click="fieldStore.setCurField(tag)" class="cursor-pointer" :key="tag.prop" closable
                    :disable-transitions="false" @close="handleCloseTr(tag)">
                    {{ tag.label }}
                  </el-tag>
                </div>

                <div class="my-3 h-1 bg-[#999]"></div>

                <div class="flex gap-4 items-center mt-4 flex-wrap">
                  <el-tag v-for="tag in filterTags" type="success" class="cursor-pointer" @click="trList.push(tag)"
                    :key="tag.prop" :disable-transitions="false">
                    {{ tag.label }}
                  </el-tag>
                </div>
              </div>

              <groupView />

              <el-button class="w-full my-8" type="danger" @click="onCreate">生成代码</el-button>


              <el-input type="textarea" :rows="10" placeholder="替换后的结果" v-model="result" readonly class="w-full mb-4" />
            </div>
          </el-tab-pane>
          <el-tab-pane label="item" name="item">item</el-tab-pane>
        </el-tabs>
      </div>

    </el-main>
  </el-container>

</template>

<script setup>
import { computed, reactive, ref } from 'vue';
import { checkDuplicateProp } from '@/comm/tool'
import settingsView from './comm/settingsView.vue';
import fieldView from './comm/fieldView.vue';
import groupView from './comm/groupView.vue';
import { useFieldStore } from '@/stores/field';
import { useGroupStore } from '@/stores/group';


const fieldStore = useFieldStore()
const groupStore = useGroupStore()
const width = ref(120)
const curTag = ref(null)
const curName = ref("")
// const filterList = ref([])
const formList = ref([])
const group = ref([])
const keyword = ref("")
const activeName = ref("list")
const drawer = ref(false)
const labelWidth = ref(120)

const onConfig = (n) => {
  console.log(n, typeof n)
  labelWidth.value = Number(n)
}

const filterList = computed(() => {
  const ary = trList.value.filter(i => i.search);
  ary.sort((a, b) => (Number(b.searchOrder) || 0) - (Number(a.searchOrder) || 0));
  console.log("ary", ary);
  return ary;
})

const newObj = ref({
  prop: '',
  label: '',
  type: ''
})

const onAdd = () => {
  const obj = {
    "type": newObj.value.type || "input",
    "span": 12,
    "order": 99,
    "addDisplay": true,
    "editDisplay": true,
    "viewDisplay": true,
    "prop": newObj.value.prop,
    "label": newObj.value.label
  }
  console.log("obj", obj)
  tabList.value.push(obj)
}

const jsonInput = ref(localStorage.getItem("str") || '');
const tabList = ref([])
const trList = ref([])
const result = ref("")
const dsName = ref("")

const filterTags = computed(() => {
  console.log("fieldStore.fields", fieldStore.fields)
  console.log("keyword", keyword.value)
  if (keyword.value) {

    return tabList.value.filter(item => {
      return item.label.includes(keyword.value)
    })
  }
  return tabList.value
})

const onSort = (type) => {
  console.log("curlist", fieldStore.curColumn)
  const index = fieldStore.curColumn.findIndex(i => i.prop === fieldStore.curField.prop);

  // 如果没有找到该元素，直接返回
  if (index === -1) return;

  const item = fieldStore.curColumn[index];

  // 移到第一位
  if (type === 1) {
    fieldStore.curColumn.splice(index, 1); // 移除当前元素
    fieldStore.curColumn.unshift(item); // 添加到数组开头
  }
  // 往前移动一个
  else if (type === 2) {
    if (index > 0) { // 确保不是第一个元素
      fieldStore.curColumn.splice(index, 1); // 移除当前元素
      fieldStore.curColumn.splice(index - 1, 0, item); // 插入到前一个位置
    }
  }
  // 往后移动一个
  else if (type === 3) {
    if (index < fieldStore.curColumn.length - 1) { // 确保不是最后一个元素
      fieldStore.curColumn.splice(index, 1); // 移除当前元素
      fieldStore.curColumn.splice(index + 1, 0, item); // 插入到后一个位置
    }
  }
  // 移到最后一位
  else if (type === 4) {
    fieldStore.curColumn.splice(index, 1); // 移除当前元素
    fieldStore.curColumn.push(item); // 添加到数组末尾
  }
}

const onRow = (item, n) => {
  item.span = 24 / n
}

const handleCloseFilter = (tag) => {
  filterList.value.splice(filterList.value.indexOf(tag), 1)
}


const handleCloseTr = (tag) => {
  trList.value.splice(trList.value.indexOf(tag), 1)
}

const deleteTag = (tag) => {
  tabList.value.splice(tabList.value.indexOf(tag), 1)
}

const onAddSearch = (tag) => {
  console.log("tag", tag)
  console.log(trList.value)
  trList.value.forEach(item => {
    if (item.prop == tag.prop) {
      item.search = true
    }
  })
}


const handleCloseForm = (list, tag) => {
  list.splice(list.indexOf(tag), 1)
}

function onInit() {
  try {
    const json = JSON.parse(jsonInput.value);
    console.log(json)
    localStorage.setItem("str", jsonInput.value)
    // checkDuplicateProp(json.column)
    dsName.value = json.dsName

    tabList.value = [...json.column];

    //分组数据
    group.value = json.group

    //查看表格列表数据
    trList.value = [...json.column];
    // filterList.value = json.column.filter(i => i.search)

    fieldStore.setFields(json.column)

    groupStore.setGroup(json.group)

    // result.value = modifiedLines.join('\n');
  } catch (error) {
    console.error('处理错误:', error);
    result.value = '处理错误，请检查输入内容。';
  }
}

const onCreate = () => {
  console.log("filterList.value", filterList.value)
  let json = JSON.parse(jsonInput.value);
  trList.value.forEach(item => {
    const res = filterList.value.find(i => i.label == item.label)
    if (res) {
      item.search = true
    }
  })
  json.column = clone(trList.value);
  json.group = clone(groupStore.group);
  // if (labelWidth.value) {
  //   json = Object.assign({ labelWidth: labelWidth.value }, json)
  // }
  addDicName(json.column)
  json.group.forEach(item => {
    addDicName(item.column)
    const labelWidth = Number(item.labelWidth) || 90

    // if (item.span) {
    item.column.forEach(i => {
      i.span = item.span || 12
      i.labelWidth = labelWidth
    })
    // }
    delete item.span
    delete item.filterColumn
    delete item.originColumn
  })
  result.value = JSON.stringify(json, null, 2)
  console.log(json)
}

const clone = (obj) => {
  return JSON.parse(JSON.stringify(obj));
}
const addDicName = (list) => {
  list.forEach(i => {
    if (i.dicName) {
      i.type = "select";
      i.dicUrl = "/system/dict/dictionary?code=" + i.dicName;
      i.props = {
        label: "dictValue",
        value: "dictKey"
      }
      delete i.dicName
    }
  })
}
</script>

<style scoped>
.cos {
  border: solid 2px rgb(239, 105, 2);
}
</style>
